package com.example.demo

import com.example.demo.singleton.VertxHolder
import com.example.demo.verticle.DatasourceVerticle
import com.example.demo.verticle.HttpServerVerticle
import io.vertx.config.ConfigRetriever
import io.vertx.config.ConfigRetrieverOptions
import io.vertx.config.ConfigStoreOptions
import io.vertx.core.DeploymentOptions
import io.vertx.core.VertxOptions
import io.vertx.core.json.JsonObject
import io.vertx.kotlin.coroutines.CoroutineVerticle
import io.vertx.kotlin.coroutines.awaitResult
import org.slf4j.LoggerFactory


class MainVerticle : CoroutineVerticle() {

  private val env = "dev"

  private val logger = LoggerFactory.getLogger(this.javaClass)

  override suspend fun start() {
    val store = ConfigStoreOptions()
      .setType("file")
      .setFormat("yaml")
      .setConfig(JsonObject().put("path", "conf/my-config-$env.yaml"))
    val retriever = ConfigRetriever.create(vertx, ConfigRetrieverOptions().addStore(store))
    val config = awaitResult<JsonObject> { retriever.getConfig(it) }
    logger.info("配置读取成功：${config}")
    vertx.close()
    val vertxConfig = config.getJsonObject("vertx")
    VertxHolder.setInstance(VertxOptions(vertxConfig))
    val newVertx = VertxHolder.getInstance()
    //配置保存在共享数据中
    val sharedData = newVertx!!.sharedData()
    val localMap = sharedData.getLocalMap<String, JsonObject>("demo")
    config.put("env", env)
    localMap["config"] = config
    try {
      //先发布数据源
      awaitResult<String> {
        newVertx.deployVerticle(DatasourceVerticle(), DeploymentOptions().setWorker(true), it)
      }
      //再发布web
      awaitResult<String> {
        newVertx.deployVerticle(HttpServerVerticle(), it)
      }
    } catch (e: Exception) {
      logger.error("发布失败：${e.message}", e)
    }
  }

  override suspend fun stop() {
    super.stop()
    logger.info("MainVerticle 停止")
  }
}
